package routes

import (
	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
	"github.com/go-redis/redis/v8"
	"github.com/morgine/redirect/internal/http/handlers"
	"gorm.io/gorm"
	"time"
)

type Options struct {
	Redis           *redis.Client
	DB              *gorm.DB
	AuthExpires     int64
	AesCryptKey     string
	DefaultAccounts []handlers.AdminAccount
}

func Register(opts *Options) (engine *gin.Engine, cancel func()) {
	admin := handlers.NewAdmin(&handlers.AdminOptions{
		DB:              opts.DB,
		Redis:           opts.Redis,
		AuthExpires:     opts.AuthExpires,
		AesCryptKey:     opts.AesCryptKey,
		DefaultAccounts: opts.DefaultAccounts,
	})
	redirect := handlers.NewRedirect(opts.DB)

	engine = newEngine()

	noAuth := engine.Group("/")
	adminAuth := engine.Group("/").Use(admin.Auth)

	// 管理员处理器路由注册
	{
		adminAuth.GET("/info", admin.Info)
		noAuth.POST("/login", admin.Login())
		adminAuth.GET("/logout", admin.Logout)
		adminAuth.PUT("/reset", admin.Reset())
	}

	// 跳转处理器路由注册
	{
		adminAuth.GET("/groups", redirect.GetGroups())
		adminAuth.PUT("/group", redirect.SaveGroup())
		adminAuth.DELETE("/group", redirect.DelGroup())

		adminAuth.GET("/links", redirect.GetLinks())
		adminAuth.PUT("/link", redirect.SaveLink())
		adminAuth.DELETE("/link", redirect.DelLinks())

		noAuth.GET("/s", redirect.GetCurrentLink())
	}
	return engine, redirect.Close
}

func newEngine() *gin.Engine {
	engine := gin.New()
	engine.Use(func(ctx *gin.Context) {
		// 可在此设置日志过滤条件

		gin.Logger()(ctx)
	})

	engine.Use(gin.Recovery())

	engine.Use(cors.New(cors.Config{
		// Set cors and db middleware
		AllowOrigins:     []string{"*"},
		AllowMethods:     []string{"*"},
		AllowHeaders:     []string{"*"},
		AllowCredentials: true,
		MaxAge:           12 * time.Hour,
	}))
	return engine
}
